package com.aischool.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.aischool.common.kit.IpKit;
import com.aischool.common.kit.Md5Kit;
import com.aischool.common.kit.VerifyCodeKit;
import com.aischool.common.model.SysUser;
import com.aischool.params.SysUserParams;
import com.aischool.utils.AppUtil;
import com.aischool.utils.DateUtil;
import com.aischool.utils.JsonCodeEnum;
import com.aischool.utils.JsonResult;
import com.aischool.utils.JwtToken;
import com.aischool.utils.RegexUtil;
import com.aischool.utils.StateEnum;
import com.aischool.utils.StringUtil;
import com.aischool.utils.SysAppEnum;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;

public class SysUserService extends BaseService{

	@Inject
	AiTeacherService aiTeacherService;
	@Inject
	AiParentService aiParentService;
	
	public SysUser dao = new SysUser().dao();
	
	public final String CK_CacheName = "CacheUser";
	public final String CK_Sys_User_Id_Pre = "sys_user_id_";
	
	public String getCacheKey(int user_id) {
		return CK_Sys_User_Id_Pre + user_id;
	}
	
	/*********************************************/
	
	/**
	 * 登录
	 */
	public JsonResult login(Controller controller) {
		JsonResult jr =new JsonResult();

		// 应用ID  
		int appid = controller.getParaToInt(0, 0);
		
		// 所在机构ID
		int orgid = 0;
		
		String username = controller.getPara("username", "");
		String password = controller.getPara("password", "");
		String checkcode = controller.getPara("verifycode", "");
		
		if (appid<=0) {
			jr.setMsg("请检查参数！");
		}else if (StrKit.isBlank(username)) {
			jr.setMsg("请输入登录账户！");
		}else if (StrKit.isBlank(password)) {
			jr.setMsg("请输入密码！");
		}else if (StrKit.isBlank(checkcode)) {
			jr.setMsg("请输入验证码！");
		}else if (!VerifyCodeKit.checkCode(checkcode, controller)) {
			jr.setMsg("验证码不正确！");
		}else {
			String md5pwd = Md5Kit.MD5For8(password); 
			// 根据用户名获取用户信息
			SysUser info = getUserInfo(username, md5pwd, appid);
			//System.err.println(info);
			if (info == null) {
				jr.setMsg("用户名或密码错误！");
			}else if(info.getIsLock()) {
				jr.setMsg("账户被锁定！");
			}else if (info.getUserState() != 1) {
				jr.setMsg("账户已禁用！");
			}else {
				boolean is_make_token = true;
				if (appid == 4 || appid == SysAppEnum.TEACHER_APP.getId()) {
					Record rd4 = aiTeacherService.getOne(info.getUserId());
					if (rd4 != null) {
						orgid = rd4.getInt("org_id");
					}else {
						is_make_token = false;
						jr.appendMsg("员工信息错误！");
					}
				}else if (appid == SysAppEnum.FAMILY_APP.getId()) {
					Record rd6 = aiParentService.getOneByUserId(info.getUserId());
					if (rd6 != null) {
						orgid = rd6.getInt("org_id");
					}else {
						is_make_token = false;
						jr.appendMsg("家长信息错误！");
					}
				}
				if (is_make_token) {
					// 生成token
					try {
						String tokenVal = info.getUserId() + "," + appid + "," + orgid;
						String sToken = JwtToken.createToken(tokenVal);
						// 设置token cookie
						//setCookie(AppUtil.Cookie_Token_Key, sToken, AppUtil.Cookie_maxAgeInSeconds, AppUtil.Cookie_Path);
						AppUtil.setCookie(controller.getRequest(), controller.getResponse(), AppUtil.getCookieTokenKey(controller), sToken, AppUtil.Cookie_maxAgeInSeconds);
						
						jr.setDicKV("auth_token", sToken);
						
						// 登录成功，更新登录信息
						info.setLoginTime(DateUtil.getTimestamp());
						info.setLoginIp(IpKit.getRealIp(controller.getRequest()));
						String strtmp = controller.getPara("login_lng");
						info.setLoginLat(StrKit.notBlank(strtmp)?new BigDecimal(strtmp):null);
						strtmp = controller.getPara("login_lat");
						info.setLoginLat(StrKit.notBlank(strtmp)?new BigDecimal(strtmp):null);
						strtmp = controller.getPara("device_code");
						if (StrKit.notBlank(strtmp)) {
							info.setLoginDeviceCode(strtmp);
						}
						info.setUpdateTime(DateUtil.getTimestamp());
						info.setErrNum(0);
						info.update();
						
						// 清除验证码cookie
						VerifyCodeKit.removeCookie(controller);
						
						jr.setEnum(JsonCodeEnum.Success_User_Logined);
					}catch(Exception ex) {
						// 生成token失败，程序终止
						jr.setMsg("系统错误，生成Token失败！");
					}
				}
			}
			
		}
		
		return jr;
	}

	/**
	 * 退出登录
	 */
	public JsonResult logout(Controller controller) {
		JsonResult jr = new JsonResult();
		controller.removeCookie(AppUtil.getCookieTokenKey(controller));
		jr.setEnum(JsonCodeEnum.Success_User_Logout);
		return jr;
	}
	
	public JsonResult updateInfo(Controller controller) {
		JsonResult jr = new JsonResult();

		int user_id = controller.getAttrForInt("login_user_id");
		SysUser info = new SysUser();// sysUserService.getUserInfo(user_id);
		info.setUserId(user_id);
		info.removeNullValueAttrs();
		info.setUserMobile(controller.getPara("user_mobile", ""));
		info.setUserEmail(controller.getPara("user_email", ""));
		info.setUserName(controller.getPara("user_name", ""));
		boolean bf = info.update();
		if (bf) {
			removeCache(user_id);
			jr.setEnum(JsonCodeEnum.Success);
		}
		return jr;
	}
	
	public JsonResult updatePwd(Controller controller) {
		JsonResult jr = new JsonResult();

		int user_id = controller.getAttrForInt("login_user_id");
		String oldpwd = controller.getPara("oldpwd","");
		String newpwd = controller.getPara("newpwd","");
		String newpwd2 = controller.getPara("newpwd2","");
		
		SysUser info = getUserInfo(user_id);
		
		if (StrKit.isBlank(oldpwd)) {
			jr.appendMsg("请输入原密码！");
		}else if (StrKit.isBlank(newpwd)) {
			jr.appendMsg("请输入新密码！");
		}else if (StrKit.isBlank(newpwd2)) {
			jr.appendMsg("请输入新密码确认！");
		}else if (!newpwd.equals(newpwd2)) {
			jr.appendMsg("两次输入的新密码不一致！");
		}else if(info == null){
			jr.appendMsg("用户数据错误！");
		}else if(!info.getLoginPwd().equals(Md5Kit.MD5For8(oldpwd))){
			jr.appendMsg("原密码错误！");
		}else {
			info.setLoginPwd(Md5Kit.MD5For8(newpwd));
			info.removeNullValueAttrs();
			boolean bf = info.update();
			if (bf) {
				removeCache(user_id);
				jr.setEnum(JsonCodeEnum.Success);
			}
		}
		
		return jr;
	}
	
	public SysUser getUserInfo(String username, String password, int appid) {
		return dao.findFirst("SELECT a.* FROM sys_user a \r\n" + 
				"INNER JOIN sys_user_app b ON b.user_id = a.user_id \r\n" + 
				"WHERE a.login_name = ? AND a.login_pwd = ? AND b.app_id = ?", 
				username, password, appid);
	}
	
	public Record getUserByMobile(String user_mobile) {
		return Db.findFirst("SELECT a.* FROM sys_user a WHERE a.user_mobile = ?", user_mobile);
	}
	
	public Record getUserByLoginName(String login_name) {
		return Db.findFirst("SELECT a.* FROM sys_user a WHERE a.login_name = ?", login_name);
	}
	
	public SysUser getUserInfo(int user_id) {
		Record rd = getUser(user_id);
		if (rd !=null) {
			return new SysUser().put(rd);
		}
		return null;
	}
	
	/**
	 * 获取单个用户
	 * @param user_id
	 * @return
	 */
	public Record getUser(int user_id) {
		String sql = "SELECT a.* FROM sys_user a WHERE a.user_id = ?";
		return Db.findFirstByCache(CK_CacheName, getCacheKey(user_id), sql, user_id);
	}
	
	/**
	 * 获取分页数据
	 * @param params
	 * @return
	 */
	public Page<Record> getPage(SysUserParams params){
		String sql_select = "SELECT a.* ";
		String sql_from   =	"FROM sys_user a "
							+ "INNER JOIN sys_user_app b ON b.user_id = a.user_id ";
		String sql_where  =	"WHERE a.user_state >= 0 ";
		String sql_order = " ORDER BY a.user_id DESC";
		
		List<Object> listObj = new ArrayList<Object>();
		if (params.getState() != StateEnum.ALL.getState()) {
			sql_where =	"WHERE a.user_state = ?";
			listObj.add(params.getState());
		}
		
		if(params.getAppId() > 0) {
			sql_where += " AND b.app_id = ? ";
			listObj.add(params.getAppId());
		}
		
		if (StrKit.notBlank(params.getKeywords())) {
			sql_where += this.getLinkWords(sql_where) + " a.login_name LIKE ? ";
			listObj.add("%" + params.getKeywords() + "%");
		}
		return Db.paginate(params.getPageNo(), params.getPageSize(), sql_select, sql_from + sql_where + sql_order, listObj.toArray());
	}
	
	public boolean updateWxOpenId(int user_id, String wxOpenid, String headimgurl) {
		Db.update("UPDATE sys_user SET user_img = ? WHERE user_id = ? AND (user_img IS NULL OR user_img = '')", headimgurl, user_id);
		int ir = Db.update("UPDATE sys_user SET wx_openid = ? WHERE user_id = ?", wxOpenid, user_id);
		if (ir>0) {
			CacheKit.remove(CK_CacheName, getCacheKey(user_id));
		}
		return ir > 0;
	}
	
	public boolean delUser(int user_id) {
		int ir = Db.update("DELETE FROM sys_user WHERE user_id > 1 AND user_id = ?", user_id);
		if (ir>0) {
			CacheKit.remove(CK_CacheName, getCacheKey(user_id));
		}
		return ir > 0;
	}
	

	public boolean delMore(String ids) {
		if (StrKit.isBlank(ids)) {
			return false;
		}
		if (RegexUtil.isSqlIds(ids)) {
			ids = StringUtil.trim(ids, ',');
			int ir = Db.delete("DELETE FROM sys_user a " + 
					"USING (SELECT regexp_split_to_table(COALESCE(?,''),E',') AS ids) AS tt " +
					"WHERE a.user_id > 1 AND a.user_id = CAST(tt.ids AS INTEGER)", 
					StringUtil.trim(ids, ','));
			if (ir > 0) {
				String[] arr1 = ids.split(",");
				for(int i=0;i<arr1.length;i++) {
					removeCache(Integer.parseInt(arr1[i]));
				}
			}
			return ir > 0;
		}
		
		return false;
	}
	
	public void removeCache(int user_id) {
		CacheKit.remove(CK_CacheName, getCacheKey(user_id));
	}
}
